#!/bin/bash

# 设置变量
CJSON_VERSION="1.7.14"  # 修改为您需要的 cJSON 版本
CJSON_TAR="cJSON-${CJSON_VERSION}.tar.gz"
CJSON_URL="https://github.com/DaveGamble/cJSON/archive/refs/tags/v${CJSON_VERSION}.tar.gz"
INSTALL_PREFIX="/home/luke/project/tools/install/json/"  # 修改为您的安装路径
CROSS_COMPILE="aarch64-linux-musleabi-"  # 修改为您的交叉编译前缀，例如 arm-linux-gnueabi-

# 下载源代码
if [ ! -f "${CJSON_TAR}" ]; then
    echo "Downloading ${CJSON_TAR}..."
    wget "${CJSON_URL}" -O "${CJSON_TAR}"
fi

# 解压源代码
if [ ! -d "cJSON-${CJSON_VERSION}" ]; then
    echo "Extracting ${CJSON_TAR}..."
    tar -xzf "${CJSON_TAR}"
fi

# 进入源代码目录
cd "cJSON-${CJSON_VERSION}" || exit

# 修改 Makefile 以使用交叉编译工具链
sed -i "s/^CC = gcc/CC = ${CROSS_COMPILE}gcc/" Makefile
sed -i "s/^AR = ar/AR = ${CROSS_COMPILE}ar/" Makefile

# 编译
echo "Building cJSON..."
make

# 安装
echo "Installing cJSON..."
make install DESTDIR=${INSTALL_PREFIX}

# 清理
cd ..
rm -rf "cJSON-${CJSON_VERSION}"
echo "Cleaning up..."

echo "cJSON ${CJSON_VERSION} has been cross-compiled and installed successfully."
